package com.mk.cloud.common.service.core;


import act.app.ActionContext;
import act.controller.Controller;
import act.util.Global;
import com.mk.cloud.common.enums.ErrorCode;
import com.mk.cloud.common.exception.UserException;
import org.osgl.exception.UnexpectedException;
import org.osgl.mvc.annotation.Catch;
import org.osgl.mvc.result.Result;
import org.osgl.util.C;
import org.rythmengine.exception.CompileException;

import javax.inject.Singleton;

@SuppressWarnings("unused")
@Singleton
public class ExceptionService extends Controller.Base {

    @Catch @Global
    public Result internalHandle(Exception e, ActionContext context) {
        if (e instanceof UnexpectedException) {
            return handel(ErrorCode.E200001.status(), e.getMessage(), context);
        } else if (e instanceof UserException) {
            UserException ex = (UserException) e;
            return handel(ex.getStatus(), e.getMessage(), context);
        } else if (e instanceof NullPointerException) {
            return handel(ErrorCode.E200000.status(), e.getMessage(), context);
        } else if (e instanceof CompileException) {
            return null;
        } else {
            return handel(ErrorCode.E100001.status(), e.getMessage(), context);
        }
    }

    private Result handel(String status, String message, ActionContext context) {
        return renderJson(C.map("status", status, "message", message));
    }
}
